﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using MINERP.StartOrder.IView;
using MINERP.BLL.StartOrder;
using MINERP.MODEL.StartOrder;
using MINERP.MODEL.FoundationModel;
using MINERP.COM;
using Leadtools.Codecs;
using System.IO;
using System.Runtime.InteropServices;
using System.Net;
using ServiceInterfaces.DataContracts;
using ServiceInterfaces.ServiceInterfaces;
using System.ServiceModel;
using System.Windows.Forms;
using System.ComponentModel;
using System.Net.Sockets;
using System.Configuration;
using MINERP.StartOrder.Forms;


namespace MINERP.StartOrder.Presenter
{
    public class FrmMainPresenter
    {

        private IMainView _view;
        private OrderBLL _bll = new OrderBLL();

        private List<ShopInfo_Order> _shopList = new List<ShopInfo_Order>(); //商户列表
        private ShopInfo_Order _curentShopInfo = null; //当前商户
        private string _unit = string.Empty; //单位
        private List<OrderInfo> _orderInfoList = new List<OrderInfo>(); //待开单产品列表

        private Dictionary<int, List<ProductTempleteInfo>> _shopProductTempleteList =
            new Dictionary<int, List<ProductTempleteInfo>>(); //商户产品列表

        private List<PaperType_Info> _PaperTypeInfoList = new List<PaperType_Info>(); //某商户已勾选纸型列表
        private List<PaperFace_Info> _PaperFaceInfoList = new List<PaperFace_Info>(); //有效纸面列表，纸型表中状态1为有效，2为停用，3为删除

        private List<ServiceInterfaces.DataContracts.Printer_Info> _printerList =
            new List<ServiceInterfaces.DataContracts.Printer_Info>(); //打印机列表

        private List<User_Info> _userList = new List<User_Info>(); //全部有效员工列表
        private int orderID = 0; //订单id
        public string bagCode = string.Empty; //订单编号
        private string ComputerName; //开单电脑名称
        private int TryTimes = 0; //重新尝试连接次数
        private bool _IsNeedCheckPhotoRepeat; //是否检查重复开单

        private TcpClient client = null; //tcp客户端(crc验证通信使用)
        private Socket clientSocket = null; //socket客户端(crc验证通信使用)

        public delegate void RefreshMovePhotoProcessHander(List<MoveOrderInfo> moveOrderInfoList); //刷新移动照片进程委托
        public event RefreshMovePhotoProcessHander RefreshMovePhotoProcessEvent; //刷新移动照片进程事件

        public delegate void ShowMoveMsgHander(string msg); //显示照片移动状态委托
        public event ShowMoveMsgHander showMoveMsgEvent; //显示照片移动状态事件

        public delegate void ShowOrderBagCodeHander(string msg); //显示订单号
        public event ShowOrderBagCodeHander showOrderBagCodeEvent; //显示订单号事件

        private bool UseAutoSelectShop = false; //是否使用系统根据文件夹名称自动找到的商户

        //public delegate void ShowFormMsgHander(string msg);//子线程想主线程（主窗体）显示消息 委托
        //public event ShowFormMsgHander showFormMsgEvent;////子线程想主线程（主窗体）显示消息 事件

        //public delegate void CloseProcessBarFromHander();//关闭进度条委托
        //public event CloseProcessBarFromHander closeProcessBarFormEvent;//关闭进度条事件

        //public delegate void ShowProcessBarFormHander();//显示进度条委托
        //public event ShowProcessBarFormHander showProcessBarFormEvent;//显示进度条事件







        //API
        /// <summary>
        /// 移动文件，文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <param name="flag">1如果文件存在，则替换；2如移动到不同的卷，则复制文件并删除原来的文件；3移动操作在系统重启后才真正执行</param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "MoveFileEx", CharSet = CharSet.Unicode)]
        public static extern bool MoveFile(string src, string dst, long flag);


        public FrmMainPresenter(IMainView view)
        {
            _view = view;
            RasterCodecs.Startup();
            this.ComputerName = Dns.GetHostName();
        }

        ~FrmMainPresenter()
        {
            RasterCodecs.Shutdown();
        }

        /// <summary>
        /// 绑定有效商户
        /// </summary>
        public void BindShop()
        {
            _shopList = GetShopList();
            //if (_shopList.Count < 1)
            //{
            //    IShopAndProductTemplete productTempleteManger = null;
            //    try
            //    {
            //        productTempleteManger = ServiceBroker.FindService<IShopAndProductTemplete>();
            //        _shopList = productTempleteManger.GetShopInfo();
            //    }
            //    catch (Exception ex)
            //    {
            //        throw ex;
            //    }
            //    finally
            //    {
            //        ServiceBroker.DisposeService<IShopAndProductTemplete>(productTempleteManger);
            //    }
            //}

            _view.BindShop(_shopList);
        }

        /// <summary>d
        /// 商户列表
        /// </summary>
        public List<ShopInfo_Order> ShopList
        {
            get
            {
                if (_shopList.Count < 1)
                {
                    _shopList = GetShopList();
                }
                return _shopList;
            }
        }

        /// <summary>
        /// 绑定纸型
        /// </summary>
        /// <param name="shopId"></param>
        public void BindPaperType(int shopId)
        {
            //if (_PaperTypeInfoList.Count < 1)
            _PaperTypeInfoList = _bll.GetShopPaperTypeInfoList(shopId);

            _view.BindShopPaperType(_PaperTypeInfoList);
            _view.BindOrderInfoPaperType(_PaperTypeInfoList);
            _view.BindPhotoInfoPaperType(_PaperTypeInfoList);
        }

        /// <summary>
        /// 绑定纸面
        /// </summary>
        public void BindPaperFace()
        {
            //if(_PaperFaceInfoList.Count <1)
            _PaperFaceInfoList = _bll.GetPaperFaceInfoList();

            _view.BindPaperFace(_PaperFaceInfoList);

            _view.BindPhotoInfoPaperFace(_PaperFaceInfoList);

            _view.BindOrderInfoPaperFace(_PaperFaceInfoList);
        }

        /// <summary>
        /// 加载界面时绑定所有打印机
        /// </summary>
        public void BindAllPrinter()
        {
            _printerList = _bll.GetPrinterList();
            _view.BinAllPrinter(_printerList);

        }

        /// <summary>
        /// 绑定产品纸型
        /// </summary>
        public void BindOrderInfoPaperType()
        {
            if (_PaperTypeInfoList.Count < 1)
            {
                _PaperTypeInfoList = _bll.GetShopPaperTypeInfoList(_curentShopInfo.ShopId);
            }
            _view.BindOrderInfoPaperType(_PaperTypeInfoList);
        }

        /// <summary>
        /// 绑定产品纸面
        /// </summary>
        public void BindOrderInfoPaperFace()
        {
            if (_PaperFaceInfoList.Count < 1)
            {
                _PaperFaceInfoList = _bll.GetPaperFaceInfoList();
            }
            _view.BindOrderInfoPaperFace(_PaperFaceInfoList);
        }

        /// <summary>
        /// 绑定照片纸型
        /// </summary>
        public void BindPhotoInfoPaperType()
        {
            if (_PaperTypeInfoList.Count < 1)
            {
                _PaperTypeInfoList = _bll.GetShopPaperTypeInfoList(_curentShopInfo.ShopId);
            }
            _view.BindPhotoInfoPaperType(_PaperTypeInfoList);
        }

        /// <summary>
        /// 绑定照片纸型
        /// </summary>
        public void BindPhotInfoPaperFace()
        {
            if (_PaperFaceInfoList.Count < 1)
            {
                _PaperFaceInfoList = _bll.GetPaperFaceInfoList();
            }
            _view.BindPhotoInfoPaperFace(_PaperFaceInfoList);
        }


        /// <summary>
        /// 绑定员工
        /// </summary>
        public void BindUsers()
        {
            if (_userList.Count < 1)
            {
                _userList = _bll.GetUserInfoList();
            }
            _view.BindUserInfoList(_userList);
        }

        /// <summary>
        /// 绑定商户产品模版
        /// </summary>
        /// <param name="shopId"></param>
        public void BindProductTemplete(int shopId)
        {
            if (_shopProductTempleteList.Keys.Contains(shopId))
            {
                var prList = _shopProductTempleteList.First(s => s.Key == shopId).Value.ToList();
                //var pr = prList.FirstOrDefault(p => p.ProuctId == 5);
                //if (pr != null)
                //{
                //    WriteLogForCheck.WriteLogFile("oldpr:CoverHeight" + pr.CoverHeight + ",CoverWidth" + pr.CoverWidth);
                //}
                _view.BindProudctTemplete(prList);
            }
            else
            {
                List<ProductTempleteInfo> productTempleteInfoList; //某商户产品模版列表
                //productTempleteInfoList = _bll.GetShopProductList(shopId, _unit);
                productTempleteInfoList = GetProductTempleteList(shopId, this._unit);
                _view.BindProudctTemplete(productTempleteInfoList);
                _shopProductTempleteList.Add(shopId, productTempleteInfoList);
            }
        }



        /// <summary>
        /// 后台加载产品模版
        /// </summary>
        public void BackgroundLoadProductTemplete()
        {
            try
            {
                _shopProductTempleteList = _bll.GetAllShopProductTempleteList(this._unit);
                //LoadProductTemplete();
            }
            catch
            {
            }
        }


        /// <summary>
        /// 从服务端取所有商户产品模版
        /// </summary>
        public void LoadProductTemplete()
        {
            IShopAndProductTemplete productTemplete = null;
            try
            {
                productTemplete = ServiceBroker.FindService<IShopAndProductTemplete>();
                foreach (var item in _shopList)
                {
                    if (!_shopProductTempleteList.Keys.Contains(item.ShopId)) //该商户的产品模版还未加载
                    {
                        List<ProductTempleteInfo> productTempleteInfoList =
                            productTemplete.GetProductTempleteList(item.ShopId, _unit);
                        _shopProductTempleteList.Add(item.ShopId, productTempleteInfoList);
                    }
                    Thread.Sleep(500);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ServiceBroker.DisposeService<IShopAndProductTemplete>(productTemplete);
            }
        }

        /// <summary>
        /// 刷新商户产品模版
        /// </summary>
        /// <param name="shopid"></param>
        public void RefreshShopProductTemplete(int shopId)
        {
            if (_shopProductTempleteList.Keys.Contains(shopId))
            {
                _shopProductTempleteList.Remove(shopId);

                List<ProductTempleteInfo> productTempleteInfoList; //某商户产品模版列表
                //productTempleteInfoList = _bll.GetShopProductList(shopId, this._unit);
                productTempleteInfoList = _bll.GetProductTempleteList(shopId, this._unit);
                _view.BindProudctTemplete(productTempleteInfoList);
                _shopProductTempleteList.Add(shopId, productTempleteInfoList);
            }
            else
            {
                List<ProductTempleteInfo> productTempleteInfoList; //某商户产品模版列表
                //productTempleteInfoList = _bll.GetShopProductList(shopId, this._unit);
                productTempleteInfoList = _bll.GetProductTempleteList(shopId, this._unit);
                _view.BindProudctTemplete(productTempleteInfoList);
                _shopProductTempleteList.Add(shopId, productTempleteInfoList);
            }
        }

        /// <summary>
        /// 通过助记码查找产品模版
        /// </summary>
        /// <param name="mnemonicCode"></param>
        /// <param name="?"></param>
        public void SearchProductTempleteByMnemonicCode(string mnemonicCode, int shopId)
        {
            List<ProductTempleteInfo> productTempleteInfoList =
                _shopProductTempleteList.First(s => s.Key == shopId).Value;
            List<ProductTempleteInfo> tempList = new List<ProductTempleteInfo>();
            foreach (var item in productTempleteInfoList)
            {
                if (item.MnemonicCode.Contains(mnemonicCode))
                {
                    tempList.Add(item);
                }
            }
            _view.BindProudctTemplete(tempList);
        }

        /// <summary>
        /// 通过助记码查找商户
        /// </summary>
        /// <param name="mnenonicCode"></param>
        public void SearchShopByMnemonicCode(string mnenonicCode)
        {
            List<ShopInfo_Order> tempList = new List<ShopInfo_Order>();
            foreach (var item in _shopList)
            {
                if (item.MnemonicCode.Contains(mnenonicCode))
                {
                    tempList.Add(item);
                }
            }
            _view.BindShop(tempList);
        }

        /// <summary>
        /// 绑定产品文件夹
        /// </summary>
        /// <param name="path"></param>
        public void BindOrderProduct(string path, bool orderByCtmFolder)
        {
            //在产品列表是空的时候才会智能找商户
            UseAutoSelectShop = false;

            if (_orderInfoList.Count() == 0)
            {
                List<ShopInfo_Order> selectShopList = new List<ShopInfo_Order>();
                ShopInfo_Order selectShop = new ShopInfo_Order();
                string[] strParas = path.Split('\\');
                selectShopList = _shopList.FindAll(delegate(ShopInfo_Order shop)
                {
                    bool isCont = false;
                    foreach (string str in strParas)
                    {
                        if (shop.ShopName.Contains(str))
                        {
                            isCont = true;
                        }

                    }
                    return isCont;

                });
                if (selectShopList.Count() > 1)
                {
                    MINERP.StartOrder.Forms.FrmSelectShop fss = new MINERP.StartOrder.Forms.FrmSelectShop();
                    fss.UnSelectShop = selectShopList;
                    if (DialogResult.OK == fss.ShowDialog())
                    {
                        _view.ClearShopMin();
                        selectShop = fss.SelectShop;
                        ShopInfo_Order shop = selectShop;
                        _view.SelectShop(selectShop.ShopName);
                        BindProductTemplete(selectShop.ShopId);
                        BindPaperType(selectShop.ShopId);
                        BindPaperFace();
                        SetCurrentShopInfo(shop);
                    }
                    else
                    {
                        //未选择不处理
                    }
                }
                else if (selectShopList.Count == 1)
                {
                    FrmSelectOneShop frm = new FrmSelectOneShop(selectShopList[0].ShopName);
                    frm.aplydefaultShopEvent += new FrmSelectOneShop.AplydefaultShopHander(frm_aplydefaultShopEvent);
                    frm.ShowDialog();

                    if (UseAutoSelectShop)
                    {
                        _view.ClearShopMin();
                        _view.SelectShop(selectShopList[0].ShopName);
                        BindProductTemplete(selectShopList[0].ShopId);
                        BindPaperType(selectShopList[0].ShopId);
                        BindPaperFace();
                        SetCurrentShopInfo(selectShopList[0]);
                    }

                }
            }


            bool flag = GetOrderInfoByCtmFolderPath(path, orderByCtmFolder);
            foreach (var item in _orderInfoList)
            {
                //crc校验
                if (_IsNeedCheckPhotoRepeat)
                {
                    try
                    {
                        int repeatPhotoId = 0;
                        bool ret = IsExsitCRC(item, out repeatPhotoId);
                        if (ret)
                        {
                            PhotoInfo photo =
                                item.Photos.Where(p => p.isPictrue == true).OrderBy(p => p.PhotoLength).First(); //最小的照片
                            MessageBox.Show("照片：" + photo.PhotoName + " 已经开过单,之前开单照片号为:" + repeatPhotoId + "，请检查！", "确定",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("照片重复验证服务端异常或服务未启动。如果要执行验证，请重启服务，再重启开单！。", "确定", MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                }
            }
            _view.BindOrderProduct(_orderInfoList, flag);
            _view.BindPrinter(_bll.GetPrinterList()); //绑定打印机列表
            _view.BindCommonChargeItem(_bll.GetCommonChargeItemInfoList(this._curentShopInfo.ShopId));
        }

        void frm_aplydefaultShopEvent(bool flag)
        {
            UseAutoSelectShop = flag;
        }

        /// <summary>
        /// 添加成品产品
        /// </summary>
        /// <param name="productTempleteInfo"></param>
        public OrderInfo AddGoodsOrderInfo(ProductTempleteInfo productTemplete)
        {
            OrderInfo oi = new OrderInfo();
            try
            {

                oi.Unit = _unit;
                oi.PaperFaceName = _view.PaperFaceInfo.Name;
                oi.PapeTypeName = _view.PaperTypeInfo.Name;
                oi.workFlows = _bll.WorkFlowListInfo;
                oi.Height = productTemplete.Height;
                oi.OrderProductCode = "2222222222";
                oi.OrderProductName += "_" + productTemplete.ProductName;
                oi.CtmName = productTemplete.ProductName;
                oi.ProductId = productTemplete.ProuctId;
                oi.IsExistProductTemplete = true;
                oi.Width = productTemplete.Width;
                oi.Height = productTemplete.Height;
                oi.CoverHeight = productTemplete.CoverHeight;
                oi.CoverWidth = productTemplete.CoverWidth;
                oi.ProductTypeCode = productTemplete.ProductTypeCode;
                oi.Remark = oi.OrderProductName + "\\";
                oi.Photos = new List<PhotoInfo>();
                oi.ProductNum = 1;
                oi.OrderPath = string.Empty;
                oi.OrilOrderPath = string.Empty;
                foreach (var item in oi.workFlows) //设置产品要经过的流程节点
                {
                    if (productTemplete.WorkOrderFlowList.Exists(w => w.TechId == item.TechId))
                    {
                        item.IsUsefull = true;
                        item.UserName = productTemplete.WorkOrderFlowList.First(w => w.TechId == item.TechId).UserName;
                    }
                    else
                    {
                        item.IsUsefull = false;
                    }
                }
                if (productTemplete.DefaultPrinter != null) //产品存在默认打印机
                {
                    oi.DefaultPrinterName = productTemplete.DefaultPrinter.PName;
                }
                else //不存在默认打印机
                {
                    oi.DefaultPrinterName = string.Empty;
                }
                if (productTemplete.OutProcessShopList.FirstOrDefault(o => o.IsDefaultOurProcessShop == true) != null)
                    //存在默认委外商
                {
                    oi.DefaultOutShopName =
                        productTemplete.OutProcessShopList.FirstOrDefault(o => o.IsDefaultOurProcessShop == true)
                            .OutShopName;
                }
                else
                {
                    oi.DefaultOutShopName = string.Empty;
                }

                //绑定的附加收费项目
                List<TechCommonChargeItemInfo> techCommChargeItemList = productTemplete.techCommonChargeItemInfoList;
                foreach (var item in productTemplete.productCommonChargeItemInfoList)
                {
                    if (!techCommChargeItemList.Exists(t => t.CommonChargeItemName == item.CommonChargeItemName))
                        //如果节点绑定的附加收费中不存在这一附加收费项，则添加
                    {
                        TechCommonChargeItemInfo techcomm = new TechCommonChargeItemInfo()
                        {
                            CommonChargeItemId = item.CommonChargeItemId,
                            CommonChargeItemName = item.CommonChargeItemName,
                            TechId = oi.workFlows.OrderBy(w => w.WorkOrder).First().TechId, //初始化为开单节点
                            TechName = oi.workFlows.OrderBy(w => w.WorkOrder).First().TechName
                        };
                        techCommChargeItemList.Add(techcomm);
                    }
                }

                oi.techCommonChargeItemInfoList = techCommChargeItemList;

                _orderInfoList.Add(oi);
                _view.BindOrderProduct(_orderInfoList, false);


                _view.SetCommonChargeItem(productTemplete.techCommonChargeItemInfoList, oi.workFlows);

                _view.BindPrinter(_bll.GetPrinterList()); //绑定打印机列表
                _view.BindOutShop(productTemplete.OutProcessShopList);
                _view.BindCommonChargeItem(_bll.GetCommonChargeItemInfoList(this._curentShopInfo.ShopId));
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return oi;
        }

        /// <summary>
        /// 清除待开单产品列表
        /// </summary>
        public void ClearOrderProduct()
        {
            _orderInfoList.Clear();
            _view.BindOrderProduct(_orderInfoList, false);
        }

        /// <summary>
        /// 刷新待开单产品列表
        /// </summary>
        public void RefreshOrderProduct()
        {
            _view.BindOrderProduct(_orderInfoList, false);
        }

        /// <summary>
        /// 设置当前商户
        /// </summary>
        /// <param name="shopInfo"></param>
        public void SetCurrentShopInfo(ShopInfo_Order shopInfo)
        {
            this._curentShopInfo = shopInfo;
        }

        /// <summary>
        /// 设置照片尺寸单位
        /// </summary>
        /// <param name="unit"></param>
        public void SetUnit(string unit)
        {
            this._unit = unit;
        }

        /// <summary>
        /// 设置是否检查照片重复
        /// </summary>
        /// <param name="isCheckCRC"></param>
        public void SetCheckCRC(bool isCheckCRC)
        {
            _IsNeedCheckPhotoRepeat = isCheckCRC;
        }

        /// <summary>
        /// 根据客户文件夹路径取得该客户的产品列表
        /// </summary>
        /// <param name="path"></param>
        /// <returns>true 有产品照片已经在开单区 ，false 正常</returns>
        private bool GetOrderInfoByCtmFolderPath(string path, bool orderByCtmFolder)
        {
            bool ret = _bll.GetOrderInfoByCtmFolderPath(path, _orderInfoList, this._unit, _view.PaperTypeInfo,
                _view.PaperFaceInfo, this.ComputerName, orderByCtmFolder);
            _orderInfoList.ForEach(o => o.Photos.ForEach(p => p.PhotoNum = SetPhotoNum(p.PicPath)));
            if (_orderInfoList.Count < 1)
            {
                MessageBox.Show("空文件夹！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            return ret;
        }

        /// 自动处理照片分数
        private int SetPhotoNum(string inFullPath)
        {

            string strCopyRule = DataTransfer.CopyRule;
            if (string.IsNullOrEmpty(strCopyRule))
            {
                return 1;
            }
            string strNum = "1";
            try
            {
                foreach (string rule in strCopyRule.Split(','))
                {
                    string[] ruleArray = rule.Split('0');
                    if (string.IsNullOrEmpty(ruleArray[0]))
                    {
                        string strEnd = ruleArray[1];
                        int endPosition = inFullPath.LastIndexOf(strEnd);
                        strNum = "";
                        for (int i = endPosition - 1; i >= 0; i--)
                        {
                            string istr = inFullPath.Substring(i, 1);
                            if (char.IsDigit(istr, 0))
                            {
                                strNum = istr + strNum;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (!string.IsNullOrEmpty(strNum)) //符合规则
                        {
                            break;

                        }
                        else
                        {
                            continue;
                        }

                    }
                    else
                    {
                        string strHead = ruleArray[0];
                        int headPosition = inFullPath.LastIndexOf(strHead);
                        strNum = "";
                        for (int i = headPosition + 1; i < inFullPath.Length; i++)
                        {
                            string istr = inFullPath.Substring(i, 1);
                            if (char.IsDigit(istr, 0))
                            {
                                strNum = strNum + istr;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (!string.IsNullOrEmpty(strNum)) //符合规则
                        {
                            break;

                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
            catch (Exception exx)
            {

            }

            return Convert.ToInt32(string.IsNullOrEmpty(strNum) ? "1" : strNum);
        }

        /// <summary>
        /// 获得有效商户
        /// </summary>
        /// <returns></returns>
        private List<ShopInfo_Order> GetShopList()
        {
            return _bll.GetShopList();
        }


        /// <summary>
        /// 改变尺寸单位
        /// </summary>
        public void ChangeUnit(int shopId)
        {
            foreach (var item in _shopProductTempleteList.First(s => s.Key == shopId).Value)
            {
                switch (this._unit)
                {
                    case "厘米":

                        item.ProductSize = string.Format("{0}X{1}cm",
                            Math.Round((decimal) (item.Width*2.54), 2, MidpointRounding.AwayFromZero),
                            Math.Round((decimal) (item.Height*2.54), 2, MidpointRounding.AwayFromZero));
                        break;
                    case "英寸":
                        item.ProductSize = string.Format("{0}X{1}inch",
                            Math.Round((decimal) item.Width, 2, MidpointRounding.AwayFromZero),
                            Math.Round((decimal) item.Height, 2, MidpointRounding.AwayFromZero));
                        break;
                    case "米":
                        item.ProductSize = string.Format("{0}X{1}m",
                            Math.Round((decimal) (item.Width*2.54/100), 2, MidpointRounding.AwayFromZero),
                            Math.Round((decimal) (item.Height*2.54/100), 2, MidpointRounding.AwayFromZero));
                        break;
                    default:
                        item.ProductSize = string.Format("{0}X{1}cm",
                            Math.Round((decimal) (item.Width*2.54), 2, MidpointRounding.AwayFromZero),
                            Math.Round((decimal) (item.Height*2.54), 2, MidpointRounding.AwayFromZero));
                        break;
                }
            }
            foreach (var item in _orderInfoList)
            {
                item.Unit = this._unit;
                foreach (var photo in item.Photos)
                {
                    photo.Unit = this._unit;
                }
            }

            _view.BindProudctTemplete(_shopProductTempleteList.First(s => s.Key == shopId).Value);
            _view.BindOrderProduct(_orderInfoList, false);

        }

        /// <summary>
        /// 删除待开单区中选中的产品
        /// </summary>
        /// <param name="oi"></param>
        public void DeleteSelectOrder(OrderInfo oi)
        {
            _orderInfoList.Remove(oi);
            _view.BindOrderProduct(_orderInfoList, false);
        }

        /// <summary>
        /// 绑定照片和产品模板
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="productTemplete"></param>
        public void BindOrderInfoAndProductTemplete(OrderInfo oi, ProductTempleteInfo productTemplete)
        {

            oi.Height = productTemplete.Height;
            oi.OrderProductCode = "2222222222";
            oi.OrderProductName += "_" + productTemplete.ProductName;
            oi.ProductId = productTemplete.ProuctId;
            oi.IsExistProductTemplete = true;
            oi.Width = productTemplete.Width;
            oi.Height = productTemplete.Height;
            oi.ProductTypeCode = productTemplete.ProductTypeCode;
            oi.Remark = oi.OrderProductName + oi.Remark + "\\";
            oi.PageNum = productTemplete.PageNum;
            oi.CoverHeight = productTemplete.CoverHeight;
            oi.CoverWidth = productTemplete.CoverWidth;
            //WriteLogForCheck.WriteLogFile("设置：CoverWidth:" + productTemplete.CoverWidth +
            //                                                 ",CoverHeight" + productTemplete.CoverHeight);
            foreach (var item in oi.workFlows) //设置产品要经过的流程节点
            {
                if (productTemplete.WorkOrderFlowList.Exists(w => w.TechId == item.TechId))
                {
                    WorkOrderFlowListInfo wflInfo = productTemplete.WorkOrderFlowList.First(w => w.TechId == item.TechId);
                    item.IsUsefull = true;
                    item.UserName = wflInfo.UserName;
                    item.WorkOrder = wflInfo.WorkOrder;
                }
                else
                {
                    item.IsUsefull = false;
                }
            }
            oi.workFlows.OrderBy(w => w.WorkOrder);
            if (productTemplete.DefaultPrinter != null) //产品存在默认打印机
            {
                oi.DefaultPrinterName = productTemplete.DefaultPrinter.PName;
                foreach (var photo in oi.Photos)
                {
                    if (photo.PhotoDPI != productTemplete.DefaultPrinter.PDPI)
                    {
                        photo.PixHeight = Convert.ToInt32(photo.Height*productTemplete.DefaultPrinter.PDPI);
                        photo.PixWidth = Convert.ToInt32(photo.Width*productTemplete.DefaultPrinter.PDPI);
                    }
                }
            }
            else //不存在默认打印机
            {
                oi.DefaultPrinterName = string.Empty;
            }

            //以产品默认纸型为准
            if (!Properties.Settings.Default.UserShopDefaultPaperType &&
                _bll.IsPaperTypeSetPrice(_curentShopInfo.ShopId, productTemplete.PaperTypeID))
            {
                oi.PapeTypeName = productTemplete.PaperTypeName;
                foreach (var photo in oi.Photos)
                {
                    photo.PaperTypeID = productTemplete.PaperTypeID;
                    photo.PaperTypeName = productTemplete.PaperTypeName;
                }
            }
            //以商户默认纸型为准
            if (!Properties.Settings.Default.UserShopDefaultPaperFace)
            {
                oi.PaperFaceName = productTemplete.PaperFaceName;
                foreach (var photo in oi.Photos)
                {
                    photo.PaperFaceId = productTemplete.PaperFaceID;
                    photo.PaperFaceName = productTemplete.PaperFaceName;
                }
            }

            if (productTemplete.OutProcessShopList.FirstOrDefault(o => o.IsDefaultOurProcessShop == true) != null)
                //存在默认委外商
            {
                oi.DefaultOutShopName =
                    productTemplete.OutProcessShopList.FirstOrDefault(o => o.IsDefaultOurProcessShop == true)
                        .OutShopName;
            }
            else
            {
                oi.DefaultOutShopName = string.Empty;
            }
            //绑定的附加收费项目
            List<TechCommonChargeItemInfo> techCommChargeItemList = productTemplete.techCommonChargeItemInfoList;
            foreach (var item in productTemplete.productCommonChargeItemInfoList)
            {
                if (!techCommChargeItemList.Exists(t => t.CommonChargeItemName == item.CommonChargeItemName))
                    //如果节点绑定的附加收费中不存在这一附加收费项，则添加
                {
                    TechCommonChargeItemInfo techcomm = new TechCommonChargeItemInfo()
                    {
                        CommonChargeItemId = item.CommonChargeItemId,
                        CommonChargeItemName = item.CommonChargeItemName,
                        TechId = oi.workFlows.OrderBy(w => w.WorkOrder).First().TechId, //初始化为开单节点
                        TechName = oi.workFlows.OrderBy(w => w.WorkOrder).First().TechName
                    };
                    techCommChargeItemList.Add(techcomm);
                }
            }

            oi.techCommonChargeItemInfoList = techCommChargeItemList;
            _view.SetCommonChargeItem(productTemplete.techCommonChargeItemInfoList, oi.workFlows);
            //_view.BindOrderProduct(_orderInfoList, false);
            _view.RefreshOrderInfo();
            //_view.RefreshPhotoInfo();
            _view.RefreshPhotoInfo(oi);
            _view.BindOutShop(productTemplete.OutProcessShopList);
        }

        /// <summary>
        /// 开单
        /// </summary>
        public void Order(object sender, DoWorkEventArgs e, DateTime fechTime, int Priority)
        {
            try
            {
                //AddOrderBagTemp(out orderID,out bagCode);
                //showProcessBarFormEvent();//显示进读条窗体
                bool isMovePhotoSuccess = MovePhotoToTempFolder(sender, e, _orderInfoList);
                if (isMovePhotoSuccess)
                {
                    _bll.AddOrderBag(sender, e, _orderInfoList, orderID, bagCode, _orderInfoList.First().CtmName,
                        Priority, _curentShopInfo.ShopId, _curentShopInfo.ShopName, DateTime.Now, fechTime, "",
                        _view.UserId);


                    //插入crc码
                    if (_IsNeedCheckPhotoRepeat == true)
                    {
                        try
                        {
                            foreach (var item in _orderInfoList)
                            {
                                AddCRC(item);
                            }
                        }
                        catch
                        {
                        } //crc校验异常不作处理
                    }

                    _orderInfoList.Clear(); //清空待开单区订单产品
                    string orderbagCode = AddOrderBagTemp(); //插入下一个订单
                    showOrderBagCodeEvent(orderbagCode);
                    _view.OrderSuccessfull = true;
                }
                else
                {
                    _view.OrderSuccessfull = false;
                    MessageBox.Show(string.Format("{0}(文件夹有文件未包含在此次开单产品中)"), "提示", MessageBoxButtons.OK,
                       MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                //closeProcessBarFormEvent();
                RebackPhto(_orderInfoList);
                _view.OrderSuccessfull = false;
                if (ex is ArgumentException)
                {
                    //showFormMsgEvent(string.Format("{0}(请检查产品模版名称是否带‘*’等非法字符)", ex.Message));
                    MessageBox.Show(string.Format("{0}(请检查产品模版名称是否带‘*’等非法字符)", ex.Message), "提示", MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
                else
                {
                    //showFormMsgEvent(ex.Message);
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        /// <summary>
        /// 检查是否所有文件夹都已经拖了产品模版
        /// </summary>
        /// <returns></returns>
        public int CheckOrder()
        {
            int ret = 0;
            foreach (var item in this._orderInfoList)
            {
                if (!item.IsExistProductTemplete)
                {
                    ret = 1;
                    return ret;
                }
            }
            foreach (var item in this._orderInfoList)
            {
                if (!item.IsFinishedGoods && item.OrilOrderPath == string.Empty)
                {
                    ret = 2;
                    return ret;
                }
            }
            return ret;
        }
        /// <summary>
        /// 移动已开单产品的照片到临时文件夹
        /// </summary>
        /// <param name="orderInfoList"></param>
        private bool MovePhotoToTempFolder2(object sender, DoWorkEventArgs e, List<OrderInfo> orderInfoList)
        {
            bool ret = true;
            int index = 0;
            try
            {
                foreach (var orderinfo in orderInfoList)
                {

                    if (((BackgroundWorker)sender).CancellationPending) //取消开单
                    {
                        RebackPhto(orderInfoList);
                        return false;
                    }
                    if (orderinfo.OrilOrderPath != string.Empty) //如果不是无照片产品
                    {
                        string path = orderinfo.OrderPath.Substring(0, orderinfo.OrderPath.LastIndexOf("\\"));
                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);
                        foreach (PhotoInfo photo in orderinfo.Photos)
                        {
                            string folder = Path.GetDirectoryName(photo.PicPath);
                            if (!Directory.Exists(folder))
                            {
                                Directory.CreateDirectory(folder);
                            }
                            if (File.Exists(photo.PicPath))
                            {
                                File.Delete(photo.PicPath);
                            }
                            bool copySucess = true;
                            try
                            {
                                File.Copy(photo.OldPicPath, photo.PicPath, true);
                            }
                            catch (Exception ex1)
                            {

                                copySucess = false;
                                throw ex1;
                            }
                            if (copySucess)
                            {
                                File.Delete(photo.OldPicPath);
                            }

                        }
                        //Directory.Move(orderinfo.OrilOrderPath, orderinfo.OrderPath);
                        // bool isAll= IsEmptyFolder(orderinfo.OrilOrderPath, orderinfo.Photos.Select(s => s.OldPicPath).ToList());
                        bool isAll = IsEmptyFolder2(orderinfo.OrilOrderPath);
                        if (isAll)
                        {
                            Directory.Delete(orderinfo.OrilOrderPath, true);

                        }
                        orderinfo.MovePhotoToTempFolderSuccefull = true;
                    }
                    index++;
                }
            }
            catch (Exception ex)
            {
                orderInfoList[index].MovePhotoToTempFolderSuccefull = false;
                ret = false;
                RebackPhto(orderInfoList);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            return ret;

        }

        /// <summary>
        /// 移动已开单产品的照片到临时文件夹
        /// </summary>
        /// <param name="orderInfoList"></param>
        private bool MovePhotoToTempFolder(object sender, DoWorkEventArgs e, List<OrderInfo> orderInfoList)
        {
            bool ret = true;
            int index = 0;
            try
            {
                foreach (var orderinfo in orderInfoList)
                {

                    if (((BackgroundWorker) sender).CancellationPending) //取消开单
                    {
                        RebackPhto(orderInfoList);
                        return false;
                    }
                    if (orderinfo.OrilOrderPath != string.Empty) //如果不是无照片产品
                    {
                        string path = orderinfo.OrderPath.Substring(0, orderinfo.OrderPath.LastIndexOf("\\"));
                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);
                        foreach (PhotoInfo photo in orderinfo.Photos)
                        {
                            string folder = Path.GetDirectoryName(photo.PicPath);
                            if (!Directory.Exists(folder))
                            {
                                Directory.CreateDirectory(folder);
                            }
                            if (File.Exists(photo.PicPath))
                            {
                                File.Delete(photo.PicPath);
                            }
                            bool copySucess = true;
                            try
                            {

                            File.Copy(photo.OldPicPath, photo.PicPath,true);
                            }
                            catch (Exception ex1)
                            {

                                copySucess = false;
                                throw ex1;
                            }
                            if (copySucess)
                            {
                                File.Delete(photo.OldPicPath);
                            }

                        }
                        //Directory.Move(orderinfo.OrilOrderPath, orderinfo.OrderPath);
                      // bool isAll= IsEmptyFolder(orderinfo.OrilOrderPath, orderinfo.Photos.Select(s => s.OldPicPath).ToList());
                        bool isAll = IsEmptyFolder2(orderinfo.OrilOrderPath);
                        if (isAll)
                        {
                            Directory.Delete(orderinfo.OrilOrderPath,true);
                           
                        }
                        orderinfo.MovePhotoToTempFolderSuccefull = true;
               
                        
                    }
                    index++;
                }
            }
            catch(Exception ex)
            {
                orderInfoList[index].MovePhotoToTempFolderSuccefull = false;
                ret = false;
                RebackPhto(orderInfoList);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            return ret;
 
        }

        bool IsEmptyFolder(string inPath,List<string> expceptList)
        {
            List<string> fileList = Directory.GetFiles(inPath).ToList();
           var leftList= fileList.Except(expceptList);
            if (leftList.Count() > 0)
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        bool IsEmptyFolder2(string inPath)
        {
            DirectoryInfo directoryInfo=new DirectoryInfo(inPath);

           var fileList = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories).ToList();
            //List<string> dirList = Directory.GetDirectories(inPath).ToList();
            //var leftList = fileList.Except(expceptList);
           if (fileList.Count() > 0)
            {
                return false;
            }
            else
            {
                return true;
            }

        }

        //将已经移动到临时文件夹的照片返回到原始位置
        private void RebackPhto(List<OrderInfo> list)
        {
            foreach (var item in list)
            {
                if (item.OrilOrderPath  != string.Empty)//如果不是无照片产品
                {
                    if (item.MovePhotoToTempFolderSuccefull)
                    {
                        Directory.Move(item.OrderPath, item.OrilOrderPath);
                    }
                }
            }
        }
        /// <summary>
        /// 插入占位用的订单包,并返回订单包号
        /// </summary>
        public string  AddOrderBagTemp()
        {
            return  _bll.AddOrderBagTemp(out orderID, out bagCode, _view.UserId);
        }


        /// <summary>
        /// 绑定正在移动照片状态的产品列表
        /// </summary>
        public void BindMoveOrderInfo()
        {
            _view.BindMoveOrderInfo( _bll.GetMoveOrderInfoList(this.ComputerName));
        }

        /// <summary>
        /// 移动照片
        /// </summary>
        public  void MovePhotoToServer()
        {
            try
            {
                List<MoveOrderInfo> MoveOrderInfoList = _bll.GetMoveOrderInfoList(this.ComputerName);
                foreach (var orderinfo in MoveOrderInfoList)
                {
                    _view.IsUploadPhoto = true;
                    try
                    {
                        bool allPhotoUploadSuccess = true;          //该产品所有照片是否上传成功
                        bool orderMoveSuccess = false;              //产品是否移动成功（包括上传照片和修改状态）
                        int UploadPhotoNum = 0;                     //上传成功的照片数量
                        foreach (var photo in orderinfo.photoList)
                        {
                            string errorMsg = string.Empty;
                            bool ret = UploadPhoto(photo, out errorMsg);
                            if (!ret)                               //上传失败
                            {
                                photo.ErrorMsg = errorMsg;
                                allPhotoUploadSuccess = false;
                            }
                            else
                            {
                                UploadPhotoNum++;
                            }


                            orderinfo.PhotoNum = UploadPhotoNum + "/" + orderinfo.photoList.Count;
                            orderinfo.ProcessPosition = (UploadPhotoNum / orderinfo.photoList.Count) * 100;

                            RefreshMovePhotoProcessEvent(MoveOrderInfoList);
                            Thread.Sleep(10);

                        }
                        if (allPhotoUploadSuccess)
                        {
                            BuckUpFile(orderinfo.OrderPath);
                            orderMoveSuccess = UpdateOrderInfoMoveStatus(orderinfo.OrderInfoId);
                            if (orderMoveSuccess)
                            {
                                //DeleteOrderFolderMoveSuccess(orderinfo.LocalPath);//删除临时文件夹中的移动完成的产品文件夹
                                DeletePhotoLocal(orderinfo.photoList);
                                showMoveMsgEvent(string.Format("({0})产品 {1} 移动成功！", DateTime.Now, orderinfo.OrderInfoId));

                                //删除wh_order中的空客户文件夹
                                DirectoryInfo dirInfo = new DirectoryInfo(orderinfo.LocalPath);
                                string rootdir = dirInfo.Root + "wh_order";
                                DeleteEmptyDirectory(rootdir);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is CommunicationException)
                            showMoveMsgEvent("(" + DateTime.Now.ToString() + ")无法连接服务端，请检查本机和服务器网络连接状态以及服务端程序是否正常运行！");
                        else
                            showMoveMsgEvent("(" + DateTime.Now.ToString() + ")" + ex.Message);
                    }

                }

            }
            catch (Exception ex)
            {
                if (ex is CommunicationException)
                    showMoveMsgEvent("(" + DateTime.Now.ToString() + ")无法连接服务端，请检查本机和服务器网络连接状态以及服务端程序是否正常运行！");
                else
                    showMoveMsgEvent("(" + DateTime.Now.ToString() + ")" + ex.Message);
                Thread.Sleep(3000);
            }
            finally
            {
                _view.IsUploadPhoto = false;
            }
            Thread.Sleep(1000);
            //MovePhotoToServer();


        }

        private void DeletePhotoLocal(List<MovePhotoInfo> list)
        {
            foreach (MovePhotoInfo movePhotoInfo in list)
            {
                File.Delete(movePhotoInfo.OldPicPath);
            }
        }


        /// <summary>
        /// 上传单张照片
        /// </summary>
        /// <param name="photo">要上传的照片信息</param>
        /// <returns>true 表示上传成功 false表示上传失败</returns>
        private bool UploadPhoto(MovePhotoInfo photo,out string errorMsg)
        {
            
            bool flag = false;
            FileStream stream =null;
            IFilesLoad fileManger=null;
            errorMsg = string.Empty;
            try
            {
                fileManger = ServiceBroker.FindService<IFilesLoad>(); //创建WCF带来
                string localPath = photo.OldPicPath;
                string fileName = localPath.Substring(localPath.LastIndexOf('\\') + 1);//获得文件本地文件地址
                int maxSiz = 1024 * 10000;  //设置每次传10M                         
                stream = System.IO.File.OpenRead(localPath);    //读取本地文件
                TranFileInfo file = fileManger.GetFiles(photo.PicPath);   //更加文件名,查询服务中是否存在该文件
                if (file == null)     //表示文件不存在
                {
                    file = new TranFileInfo();
                    file.Offset = 0; //设置文件从开始位置进行数据传递
                }
                file.Name = fileName;
                file.DesFilePath = photo.PicPath;
                file.Length = stream.Length;
                file.ErorrMsg = string.Empty;
                if (file.Length == file.Offset) //如果文件的长度等于文件的偏移量，说明文件已经上传完成
                {
                    flag = true;
                  
                }
                else
                {
                    while (file.Length != file.Offset)  //循环的读取文件,上传，直到文件的长度等于文件的偏移量
                    {
                        if (file.ErorrMsg == string.Empty)
                        {
                            file.Data = new byte[file.Length - file.Offset <= maxSiz ? file.Length - file.Offset : maxSiz]; //设置传递的数据的大小
                            stream.Position = file.Offset; //设置本地文件数据的读取位置
                            stream.Read(file.Data, 0, file.Data.Length);//把数据写入到file.Data中
                            file = fileManger.UplodaFile(file);     //上传
                            flag = true;
                        }
                        else//服务器发生错误
                        {
                            //showFormMsgEvent("服务器："+file.ErorrMsg);
                            MessageBox.Show("服务器：" + file.ErorrMsg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            flag = false;
                            break;
                        }
                    }
                    
                    //fileManger.BuckUpPhoto(photo.PicPath);//备份文件
                }
            }
            catch (Exception ex)
            {
                TryTimes++;
                Thread.Sleep(1000);
                if (TryTimes < 3)
                {
                    UploadPhoto(photo,out errorMsg);
                }
                else
                {
                    errorMsg = ex.Message;
                    photo.ErrorMsg = ex.Message;
                    throw ex;
                }
                
            }
            finally
            {
                TryTimes = 0;
                if(stream !=null)
                    stream.Close();
                ServiceBroker.DisposeService<IFilesLoad>(fileManger);
            }

            return flag;
        }

        /// <summary>
        /// 修改产品的照片移动状态
        /// </summary>
        /// <param name="orderInfoId">产品Id</param>
        /// <returns>true 修改成功 false 修改失败</returns>
        private bool UpdateOrderInfoMoveStatus(int orderInfoId)
        {
            IFilesLoad fileManger = null;
            bool ret = false;
            try
            {
                fileManger = ServiceBroker.FindService<IFilesLoad>(); //创建WCF带来
                ret = fileManger.UpdateOrderMoveStatus(orderInfoId);
            }
            catch
            {

            }
            finally
            {
                ServiceBroker.DisposeService<IFilesLoad>(fileManger);
            }
            return ret;
        }

        /// <summary>
        /// 备份照片
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string BuckUpFile(string path)
        {
            IFilesLoad fileManger = null;
            string ret = "";
            try
            {
                fileManger = ServiceBroker.FindService<IFilesLoad>(); //创建WCF带来
                ret = fileManger.BuckUpPhoto(path);
            }
            catch(Exception ex)
            {
                ret = ex.Message;
            }
            finally
            {
                ServiceBroker.DisposeService<IFilesLoad>(fileManger);
            }
            return ret;
            
        }

        /// <summary>
        /// 删除临时文件夹中已经移动成功的产品文件以及照片
        /// </summary>
        /// <param name="path"></param>
        private void DeleteOrderFolderMoveSuccess(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    try
                    {
                        Directory.Delete(path, true);

                    }
                    catch
                    {
                        DeleteDirectoryExtreme(path);
                    }
                }
            }
            catch
            {
 
            }
            
        }

        #region 当目录中没有文件与子目录时，删除
        /// <summary>
        /// 删除开单文件夹下空文件夹
        /// </summary>
        /// <param name="directory"></param>
        public void DeleteEmptyOrderFolder(string Rootdirectory)
        {
            try
            {
                DirectoryInfo rootDir = new DirectoryInfo(Rootdirectory);
                foreach (var directoryInfo in rootDir.GetDirectories())
                {
                    string directory = directoryInfo.FullName;
                    if (Directory.Exists(directory))
                    {
                        DirectoryInfo parent = Directory.GetParent(directory);
                        string[] file1 = Directory.GetFiles(directory, "*.jpg", SearchOption.AllDirectories);
                        string[] file2 = Directory.GetFiles(directory, "*.tif", SearchOption.AllDirectories);
                        string[] file3 = Directory.GetFiles(directory, "*.jpeg", SearchOption.AllDirectories);
                        string[] file4 = Directory.GetFiles(directory, "*.tiff", SearchOption.AllDirectories);
                        string[] file5 = Directory.GetFiles(directory, "*.zip", SearchOption.AllDirectories);
                        string[] file6 = Directory.GetFiles(directory, "*.rar", SearchOption.AllDirectories);
                        string[] file7 = Directory.GetFiles(directory, "*.7z", SearchOption.AllDirectories);
                        string[] files = file1.Concat(file2).Concat(file3).Concat(file4).Concat(file5).Concat(file6).Concat(file7).ToArray();
                        string[] directorys = Directory.GetDirectories(directory);
                        //if (files.Length == 0 && directorys.Length == 0)
                        if (files.Length == 0)
                        {
                            try
                            {
                                Directory.Delete(directory, true);
                            }
                            catch
                            {
                                DeleteDirectoryExtreme(directory);          //强力删除目录
                            }
                            DeleteEmptyDirectory(parent.FullName);
                        }
                        else
                        {
                            DeleteEmptyDirectory(directory);
                        }
                    }
                    

                }

            }
            catch (Exception ex)
            {
                if (ex is System.IO.IOException)
                {
                    return;
                }
                else
                {
                    throw ex;
                }
            }
        }


        /// <summary>
        /// 删除临时文件夹下空客户文件夹
        /// </summary>
        /// <param name="directory"></param>
        public   void DeleteEmptyDirectory(string Rootdirectory)
        {
            try
            {
                DirectoryInfo rootDir = new DirectoryInfo(Rootdirectory);
                foreach (var directoryInfo in rootDir.GetDirectories())
                {
                    string directory = directoryInfo.FullName;
                    if (Directory.Exists(directory))
                    {
                        DirectoryInfo parent = Directory.GetParent(directory);
                        string[] file1 = Directory.GetFiles(directory, "*.jpg", SearchOption.AllDirectories);
                        string[] file2 = Directory.GetFiles(directory, "*.tif", SearchOption.AllDirectories);
                        string[] file3 = Directory.GetFiles(directory, "*.jpeg", SearchOption.AllDirectories);
                        string[] file4 = Directory.GetFiles(directory, "*.tiff", SearchOption.AllDirectories);
                        string[] file5 = Directory.GetFiles(directory, "*.zip", SearchOption.AllDirectories);
                        string[] file6 = Directory.GetFiles(directory, "*.rar", SearchOption.AllDirectories);
                        string[] files = file1.Concat(file2).Concat(file3).Concat(file4).Concat(file5).Concat(file6).ToArray();
                        string[] directorys = Directory.GetDirectories(directory);
                        if (files.Length == 0 && directorys.Length == 0)
                        {
                            try
                            {
                                Directory.Delete(directory, true);
                            }
                            catch
                            {
                                DeleteDirectoryExtreme(directory);          //强力删除目录
                            }
                            DeleteEmptyDirectory(parent.FullName);
                        }
                    }
                    
                }
               
            }
            catch (Exception ex)
            {
                if (ex is System.IO.IOException)
                {
                    return;
                }
                else
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 强力删除目录
        /// </summary>
        /// <param name="directory"></param>
        private void DeleteDirectoryExtreme(string directory)
        {
            try
            {
                DirectoryInfo dinfo = new DirectoryInfo(directory);
                dinfo.Attributes = FileAttributes.Normal;
                string[] files = Directory.GetFiles(directory);
                string[] directorys = Directory.GetDirectories(directory);
                if ((files != null && files.Length > 0) || (directorys != null || directorys.Length > 0))
                {
                    foreach (string subFile in files)
                    {
                        File.SetAttributes(subFile, FileAttributes.Normal);
                        File.Delete(subFile);
                    }
                    foreach (string subDirectory in directorys)
                    {
                        DeleteDirectoryExtreme(subDirectory);
                    }
                }
                Directory.Delete(directory);
            }
            catch { }
        }
        #endregion



        /// <summary>
        /// 删除临时站位订单包
        /// </summary>
        /// <param name="orderbagId"></param>
        public void DeleteTempOrderBag()
        {
            _bll.DeleteTempOrderBag(orderID);
        }

        /// <summary>
        /// 设置Tcp连接
        /// </summary>
        public void SetTcpConnect()
        {
            client = new TcpClient();
            try
            {
                //string server = Properties.Settings.Default.userCrcServer;
                string server = ConfigurationManager.AppSettings["RemoteIP"];
                int port = 9999;
                try
                {
                    port = Convert.ToInt32(ConfigurationManager.AppSettings["CrcPort"]);
                }
                catch
                {
                    port = 9999;
                }
                client.Connect(server, port);
                //client.Connect("192.168.1.104", 9999);
                clientSocket = client.Client;
            }
            catch (Exception exx)
            {
                if (exx is SocketException)
                {
                    SocketException se = exx as SocketException;
                    if (se.ErrorCode == 10061)
                    {
                        MessageBox.Show("照片重复验证服务端异常或服务未启动。如果要执行验证，请重启服务，再重启开单！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        /// <summary>
        /// 检查数据库中是否已经存在该照片的CRC码
        /// </summary>
        /// <param name="oi"></param>
        /// <returns></returns>
        private bool IsExsitCRC(OrderInfo oi, out int repeatPhotoId)
        {
            repeatPhotoId = 0;
            bool ret = false;
            IFilesLoad fileManger = null;
            try
            {
                if (oi != null&& oi.Photos.Count>0)
                {
                    fileManger = ServiceBroker.FindService<IFilesLoad>();
                    PhotoInfo photo = oi.Photos.Where(p => p.isPictrue == true).OrderBy(p => p.PhotoLength).First();    //最小的照片
                    byte[] fileBytes = File.ReadAllBytes(photo.OldPicPath);
                    int crcmark = Crc32.GetCRC32(fileBytes);
                    ret = fileManger.IsExsitCRC(crcmark,out repeatPhotoId);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ServiceBroker.DisposeService<IFilesLoad>(fileManger);
            }
            return ret;
        }

        /// <summary>
        /// 获取某个商户的产品模版
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="unit"></param>
        /// <returns></returns>
        public List<ProductTempleteInfo> GetProductTempleteList(int shopId, string unit)
        {
            List<ProductTempleteInfo> list = new List<ProductTempleteInfo>();
            IShopAndProductTemplete productTempleteManger = null;
            try
            {
                productTempleteManger = ServiceBroker.FindService<IShopAndProductTemplete>();
                
                list = productTempleteManger.GetProductTempleteList(shopId, unit);
                //var pr = list.FirstOrDefault(p => p.ProuctId == 5);
                //if (pr != null)
                //{
                //    WriteLogForCheck.WriteLogFile("newpr:CoverHeight" + pr.CoverHeight + ",CoverWidth" + pr.CoverWidth);
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ServiceBroker.DisposeService<IShopAndProductTemplete>(productTempleteManger);
            }
            return list;
 
        }

        /// <summary>
        /// 添加CRC码
        /// </summary>
        /// <param name="oi"></param>
        /// <returns></returns>
        private int AddCRC(OrderInfo oi)
        {
            int ret = 0;
            IFilesLoad fileManger = null;
            try
            {
                if (oi != null)
                {
                    fileManger = ServiceBroker.FindService<IFilesLoad>();
                    PhotoInfo photo = oi.Photos.Where(p => p.isPictrue == true).OrderBy(p => p.PhotoLength).First();    //最小的照片
                    byte[] fileBytes = File.ReadAllBytes(photo.PicPath);
                    int crcmark = Crc32.GetCRC32(fileBytes);
                    ret = fileManger.AddCRC(crcmark,photo.PhotoId);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ServiceBroker.DisposeService<IFilesLoad>(fileManger);
            }
            return ret;
        }

        /// <summary>
        /// 快速查找产品模版
        /// </summary>
        /// <param name="productName"></param>
        /// <param name="height"></param>
        /// <param name="width"></param>
        /// <param name="tolerance"></param>
        /// <returns></returns>
        public List<ProductTempleteInfo> FastSearchProductTemplete(string productName, double height, double width, double tolerance)
        {
            List<ProductTempleteInfo> list = new List<ProductTempleteInfo>();
            List<ProductTempleteInfo> shopProductTempleteList = _shopProductTempleteList.First(s => s.Key == _curentShopInfo.ShopId).Value;
            List<ProductTempleteInfo> temlist = new List<ProductTempleteInfo>();
            foreach (var item in shopProductTempleteList)
            {
               string [] productNames =  item.ProductCategoryDes.Split(',');
                foreach (var proName in productNames)
	            {
                    if (productName.Contains(proName))
                    {
                        if (!temlist.Exists(t => t.ProuctId == item.ProuctId))
                        {
                            temlist.Add(item);
                        }
                    }
	            }
            }
            foreach (var item in temlist)
            {
                if (height >=width)//照片的高大于宽
                {
                    if (item.Height >= item.Width)//产品模版的高大于宽
                    {
                        if (height <= item.Height + tolerance && height >= item.Height - tolerance&&width <=item.Width+tolerance&&width >=item.Width-tolerance)
                        {
                            list.Add(item);
                        }
                    }
                    else
                    {
                        if (height <= item.Width + tolerance && height >= item.Width - tolerance && width <= item.Height + tolerance && width >= item.Height - tolerance)
                        {
                            list.Add(item);
                        }
                    }
                }
                else//height<whdth
                {
                    if (item.Height < item.Width)
                    {
                        if (height <= item.Height + tolerance && height >= item.Height - tolerance && width <= item.Width + tolerance && width >= item.Width - tolerance)
                        {
                            list.Add(item);
                        }
                    }
                    else
                    {
                        if (height <= item.Width + tolerance && height >= item.Width - tolerance && width <= item.Height + tolerance && width >= item.Height - tolerance)
                        {
                            list.Add(item);
                        }
                    }
 
                }
            }
            return list;
        }


    }
}
